package com.softserveinc;

import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.softserveinc.appwidget.MovieManagerWidgetProvider;

public class WidgetConfigureActivity extends PreferenceActivity {

	private static final String TAG = WidgetConfigureActivity.class
			.getSimpleName();

	public static final String MOVIE_LIST_SIZE = "widget_movie_list_size";
	public static final String MOVIE_LIST_ORDER = "widget_movie_list_order";
	public static final String UPDATE_WIDGET_UI = "widget_update_widget_ui";
	public static final String UPDATE_WIDGET_DATA = "widget_update_widget_data";

	private int appWidgetId;

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			try {
				MovieManagerApplication application = (MovieManagerApplication) getApplication();

				application.getWidgetSettingManager().saveAppWidgetPreferences(
						appWidgetId);

				Intent intent = new Intent(
						MovieManagerWidgetProvider.APPWIDGET_CREATE);

				intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						appWidgetId);
				sendBroadcast(intent);

				Intent resultValue = new Intent();
				resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
						appWidgetId);
				setResult(RESULT_OK, resultValue);
			} catch (Exception e) {
				Log.e(TAG, "error: " + e.getMessage(), e);
			} finally {
				finish();
			}
		}
	};

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setResult(RESULT_CANCELED);

		setContentView(R.layout.widget_config);
		addPreferencesFromResource(R.xml.widget_preferences);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}

		findViewById(R.id.button_confirm_widget).setOnClickListener(
				onClickListener);

		findViewById(R.id.button_cancel_widget).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(final View v) {
						setResult(RESULT_CANCELED);
						finish();
					}
				});

	}
}
